package cc.lirns.demo.websocket.withprimordial.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lirns
 * @date 2021/7/6 15:25
 */
@Slf4j
@ServerEndpoint(value = "/test/one")
@Component
public class MyWebSocket {

    /**
     * 线程池
     */
    private static final ScheduledExecutorService SCHEDULED_THREAD_POOL = Executors.newScheduledThreadPool(5);
    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * spring容器上下文
     */
    private static ApplicationContext applicationContext = null;
    /**
     * 会话
     */
    private Session session;
    /**
     * 线程
     */
    private ScheduledFuture<?> schedule = null;


    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyWebSocket.applicationContext = applicationContext;
    }

    /**
     * 获取springbean对象
     */
    private static <T> T getSpringBean(Class<T> cls) {
        return applicationContext.getBean(cls);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        ONLINE_COUNT.incrementAndGet(); // 在线数加1
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        ONLINE_COUNT.decrementAndGet(); // 在线数减1
        if (schedule != null && !schedule.isCancelled()) {
            schedule.cancel(true);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) throws JsonProcessingException {
        this.sendMessage("Hello, " + message);
    }

    @OnError
    public void onError(Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message) {
        try {
            log.debug("服务端给客户端[{}]发送消息", session.getId());
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e.getMessage());
        }
    }

    /**
     * 根据id取泵站所有数据
     */
    private void getPumpInfoByStationFirst(String stationId) {
    }

    /**
     * 循环取plc
     */
    public void getPumpInfoByStation() {
    }


}
